﻿using System;
using Rhizome.Contract;
using Rhizome.Model;

namespace Rhizome.Internal
{
    internal sealed class RhizomeElementKeyedCollection<TItem> : IdKeyedCollection<object, TItem> where TItem : class, IIdentityAccessor<object>
    {
        private readonly RhizomeElement _parent;

        public RhizomeElementKeyedCollection(RhizomeElement parent)
        {
            if (parent == null) throw new ArgumentNullException("parent");
            _parent = parent;
        }

        protected override void InsertItem(int index, TItem item)
        {
            var e = item as RhizomeElement;
            if (e != null) e.Parent = _parent;

            base.InsertItem(index, item);
        }

        protected override void SetItem(int index, TItem item)
        {
            var e = Items[index] as RhizomeElement;
            if (e != null) e.Parent = null;
            e = item as RhizomeElement;
            if (e != null) e.Parent = _parent;

            base.SetItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            var e = Items[index] as RhizomeElement;
            if (e != null) e.Parent = null;

            base.RemoveItem(index);
        }

        protected override void ClearItems()
        {
            Items.ForEachOfType<RhizomeElement>(element => element.Parent = null);

            base.ClearItems();
        }

		
    }
}